<template>
  <div>
    <el-page-header @back="goBack"></el-page-header>
    <el-row style="padding: 0 0 2rem 0 !important; flex-direction: column">

      <el-col :span="24">
        <div style="border: 1px solid #cccccc">
          <el-descriptions :column="4" border size="mini" label-class-name="my-label">
            <el-descriptions-item label="任务名称" :span="4">{{ title }}</el-descriptions-item>
            <el-descriptions-item label="负责人">
              <el-cascader size="mini"
                           :options="optionsHeader" v-model="indicatorDetailTask.personInCharge"
                           :props="{ expandTrigger: 'hover' }" @change="handleCascaderChangeForIndicatorTask">
              </el-cascader>
            </el-descriptions-item>
            <el-descriptions-item label="计划完成时间">
              <el-date-picker size="mini"
                              v-model="indicatorDetailTask.endTime"
                              type="date"
                              placeholder="选择日期">
              </el-date-picker>
            </el-descriptions-item>
            <el-descriptions-item label="发布人">{{ indicatorDetailTask.createBy }}</el-descriptions-item>
            <el-descriptions-item label="发布时间">
              <el-date-picker size="mini" disabled
                              v-model="indicatorDetailTask.createTime"
                              type="date"
                              placeholder="选择日期">
              </el-date-picker>
            </el-descriptions-item>
          </el-descriptions>
          <el-button type="text" size="mini" @click="releaseIndicatorTask" icon="el-icon-s-flag"
                     style="margin:0 0.625rem"
                     :disabled="!isEditing && indicatorDetailTask.id !== ''">
            发布任务
          </el-button>
          <el-button type="text" size="mini" @click="editIndicatorTask" icon="el-icon-edit" style="margin:0 0.625rem"
                     :disabled="!isCreateBy || this.indicatorDetailTask.id ==''">
            编辑
          </el-button>
        </div>
      </el-col>

      <el-divider content-position="left" direction="horizontal" style="margin: 1rem 0 !important;">实施方案</el-divider>

      <el-col :span="24">
        <div style="border: 1px solid #eee;">
          <el-table :data="indicatorDetailScheme" size="mini" border header-cell-class-name="my-label">
            <el-table-column header-align="center" min-width="5%" type="index" label="序号"
                             align="center"></el-table-column>
            <el-table-column header-align="center" label="方案内容" min-width="42.5%">
              <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.schemeContent" :disabled="!isSchemeEditing"></el-input>
              </template>
            </el-table-column>
            <el-table-column header-align="center" min-width="42.5%" label="附件"
                             style="display: flex; justify-content: space-between">
              <template slot-scope="scope">
                <el-upload v-if="!scope.row.kpiSchemeAttachments || scope.row.kpiSchemeAttachments.length === 0"
                           :disabled="!isSchemeEditing"
                           :action="uploadAction" :with-credentials="true"
                           multiple
                           :on-success="(response, file, fileList) => handleSchemeSuccess(scope.row,response, file, fileList)"
                           :file-list="schemeFileLists[scope.row.index]" :show-file-list="false">
                  <el-button size="mini" type="text" icon="el-icon-paperclip"></el-button>
                </el-upload>
                <!-- 附件链接和删除按钮 -->
                <div v-for="(att, idx) in scope.row.kpiSchemeAttachments" :key="idx"
                     style="display: inline-flex; align-items: center; margin-right: 0.5rem;">
                  <el-link
                      v-if="att.filePath"
                      :href="att.filePath"
                      target="_blank"
                      type="primary"
                      size="mini"
                  >
                    {{ att.filePath.split('/').pop() }}
                  </el-link>

                  <!-- 删除按钮 -->
                  <el-button
                      v-if="isSchemeEditing"
                      size="mini"
                      type="text"
                      icon="el-icon-close"
                      @click.stop="handleDeleteSchemeAttachment(att, scope.row)"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column header-align="center" min-width="10%" label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="deleteSchemeRow(scope.$index)" :disabled="!isSchemeEditing"
                           icon="el-icon-delete"></el-button>
                <el-button type="text" size="mini" @click="addSchemeRow(scope.$index)" :disabled="!isSchemeEditing"
                           icon="el-icon-plus" v-if="scope.$index == indicatorDetailScheme.length - 1"></el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="text" size="mini" icon="el-icon-s-flag" style="margin:0 0.625rem" @click="submitScheme"
                     :disabled="!isSchemeEditing">提交
          </el-button>
          <el-tag type="success" size="mini" v-if="indicatorDetailScheme.length > 0 && indicatorDetailScheme[0]">
            审批状态：{{ indicatorDetailScheme[0].status }}
          </el-tag>
          <el-button type="text" size="mini" icon="el-icon-edit" @click="editScheme"
                     :disabled="!isPersonInCharge || indicatorDetailScheme[0].status !='未审批'">编辑
          </el-button>
        </div>
      </el-col>

      <el-divider content-position="left" direction="horizontal" style="margin: 1rem 0 !important;">工作计划</el-divider>

      <el-col :span="24">
        <div style="border: 1px solid #cccccc">
          <el-table
              ref="table" row-key="id" :data="schemeTasks" size="mini" border @selection-change="handleSelectionChange"
                    @cell-click="viewSchemeTaskStatus" style="width: 100%">
            <el-table-column type="selection" header-align="center" align="center" min-width="5%"
                             :selectable="selectableRow">
            </el-table-column>
            <el-table-column label="序号" type="index" header-align="center" align="center"
                             min-width="5%"></el-table-column>
            <el-table-column label="计划内容" header-align="center" prop="contentSummary" min-width="21%">
              <template slot-scope="scope">
                <el-input
                    v-if="isTaskEditing && scope.row.isNew"
                    size="mini"
                    v-model="scope.row.contentSummary"
                    @click.native.stop
                ></el-input>
                <span v-else class="content-link"
                      @click="handleContentClick(scope.row, $event)">{{ scope.row.contentSummary }}</span>
              </template>
            </el-table-column>
            <el-table-column label="起止时间" prop="endTime" header-align="center" min-width="15%">
              <template slot-scope="scope">
                <el-date-picker
                    size="mini"
                    class="custom-date-picker"
                    :disabled="!isTaskEditing || !scope.row.isNew"
                    v-model="scope.row.dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="完成日期"
                    @change="updateSchemeTask(scope.row)"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="责任人" prop="header" header-align="center" min-width="6%">
              <template slot-scope="scope">
                <el-cascader size="mini"
                             :options="optionsHeader" v-model="scope.row.reportBy"
                             :disabled="!isTaskEditing || !scope.row.isNew"
                             :props="{ expandTrigger: 'hover' }" :show-all-levels="false">
                </el-cascader>
              </template>
            </el-table-column>
            <el-table-column label="任务附件" header-align="center" min-width="24%">
              <template slot-scope="scope">
                <el-upload v-if="!scope.row.releaseAttachments || scope.row.releaseAttachments.length === 0"
                           :action="uploadAction" :with-credentials="true"
                           multiple :disabled="!isTaskEditing || !scope.row.isNew"
                           :on-success="(response, file, fileList) => handleTaskSuccess(scope.row,response, file, fileList)"
                           :file-list="scope.row.fileList" :show-file-list="false">
                  <el-button size="mini" type="text" icon="el-icon-paperclip"></el-button>
                </el-upload>
                <!-- 展示任务附件列表，并提供删除按钮 -->
                <div v-for="(att, idx) in scope.row.releaseAttachments" :key="idx"
                     style="display: inline-flex; align-items: center; margin-right: 0.5rem;">
                  <el-link
                      v-if="att.filePath"
                      :disabled="isTaskEditing || scope.row.isNew"
                      size="mini"
                      :href="att.filePath"
                      target="_blank"
                      type="primary">
                    {{ att.filePath.split('/').pop() }}
                  </el-link>

                  <!-- 删除按钮 -->
                  <el-button
                      v-if="isTaskEditing || scope.row.isNew"
                      size="mini"
                      type="text"
                      icon="el-icon-close"
                      @click.stop="handleDeleteTaskAttachment(att, scope.row)">
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="完成情况" header-align="center">
              <el-table-column label="完成状态" prop="statusName" header-align="center" min-width="6%" align="center">
                <template slot-scope="scope">
                  <i class="el-icon-check" v-if="scope.row.statusName === '已完成'"
                     style="color: #BDBEBCEA; font-size: 0.75rem" title="已完成"></i>
                  <i class="el-icon-circle-check" v-else-if="scope.row.statusName === '进行中'"
                     style="color: #189C05FF; font-size: 0.75rem" title="进行中"></i>
                  <i class="el-icon-warning" v-else-if="scope.row.statusName === '已延期'"
                     style="color: #b29503; font-size: 0.75rem" title="已延期"></i>
                  <i class="el-icon-question" v-else style=" font-size: 0.75rem"></i>
                </template>
              </el-table-column>
              <el-table-column label="任务完成附件" prop="completeAttachment" min-width="21%" header-align="center">
                <template slot-scope="scope">
                  <el-link style="margin-right: 0.75rem"
                           v-for="(att, idx) in scope.row.completeAttachments"
                           :key="idx" size="mini"
                           :href="att.filePath"
                           target="_blank">
                    {{ att.filePath.split('/').pop() }}
                  </el-link>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column header-align="center" min-width="7%" label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="deleteTaskRow" icon="el-icon-delete" size="mini"
                           :disabled="!isTaskEditing || !scope.row.isNew"></el-button>
                <el-button type="text" @click="addTaskRow" icon="el-icon-plus" size="mini" :disabled="!isTaskEditing"
                           v-if="scope.$index == schemeTasks.length - 1"></el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="text" size="mini" @click="releaseSchemeTask" icon="el-icon-s-flag" style="margin:0 0.625rem"
                     :disabled="!isTaskEditing">
            发布任务
          </el-button>
          <el-button type="text" size="mini" icon="el-icon-edit" style="margin:0 0.625rem" @click="editSchemeTask"
                     :disabled="!isPersonInCharge">编辑
          </el-button>
        </div>
      </el-col>

    </el-row>
  </div>
</template>

<script>
import moment from "moment";
import {optionsHeader} from "@/utils/optionsHeader";
import Sortable from "sortablejs";

export default {
  name: "KPIItemScheme",
  data() {
    return {
      kpiId: 0,
      kpiDetailId: 0,
      optionsHeader: optionsHeader,
      title: '',
      type: '',
      uploadAction: `${process.env.VUE_APP_API_BASE_URL}/file/upload`,
      indicatorDetailTask: {
        id: '',
        kpiId: this.kpiId,
        title: this.title,
        indicatorDetailId: this.kpiDetailId,
        createTime: null,
        endTime: null,
        personInCharge: '',
        createBy: '',
      },
      indicatorDetailScheme: [
        {
          id: null,
          indicatorDetailId: '',
          schemeContent: '',
          status: '未审批',
          kpiSchemeAttachments: []
        }
      ],
      schemeFileLists: [[]],
      attachmentsToDelete: [], // 存放待删除的附件id
      schemeTasks: [{
        id: '',
        sn: "",
        processInstanceId: "",
        categoryId: "3",
        title: "",
        dateRange: [],
        createTime: "",
        releaseBy: "",
        reportBy: "",
        frequency: "周",
        reportComplete: "",
        reportCount: "",
        sort:'',
        startTime: "",
        endTime: "",
        contentSummaries: [
          {
            id: "",
            taskContentId: "",
            contentSummary: ""
          }
        ],
        taskMilestones: [],
        reportAttachments: [],
        commentAttachments: [],
        completeAttachments: [],
        taskCommentSummaries: [],
        taskCompleteSummaries: [],
        taskPlanSummaries: [],
        taskCoordinateSummaries: [],
        taskHistoryDelayVOS: [],
        contentSummary: "",
        actualFinishingTime: '',
        delayApprovedDate: '',
        releaseAttachments: []
      }],
      selectedRows: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      isCreateBy: false,
      isEditing: false,
      isPersonInCharge: false,
      isSchemeEditing: false,
      isTaskEditing: false,
      sortable: null,
    }
  },
  methods: {
    handleCascaderChangeForIndicatorTask(value) {
      this.indicatorDetailTask.personInCharge = value[value.length - 1];
      console.log(this.indicatorDetailTask.personInCharge)
    },
    goBack() {
      this.$router.push({name: 'KPIDetail', params: {id: this.kpiId}});
    },
    releaseIndicatorTask() {
      const indicatorDetailTask = {
        ...this.indicatorDetailTask,
        createTime: moment().format("YYYY/MM/DD"),
        endTime: moment(this.indicatorDetailTask.endTime).format("YYYY/MM/DD"),
        type: this.type
      }
      if (!indicatorDetailTask.id) {
        // 新任务发布
        this.$http.post("/kpi/indicator/task", indicatorDetailTask).then(res => {
          if (res.data.code == 1) {
            this.$message.success("发布成功");
            this.indicatorDetailTask.id = res.data.data.id; // 设置返回的id
            this.isEditing = false; // 发布成功后退出编辑状态
          } else {
            this.$message.error("发布失败");
          }
        });
      } else {
        // 任务更新
        this.$http.post("/kpi/indicator/update_task/", indicatorDetailTask).then(res => {
          if (res.data.code == 1) {
            this.$message.success("更新成功");
            this.isEditing = false; // 更新成功后退出编辑状态
          } else {
            this.$message.error("更新失败");
          }
        });
      }
    },
    editIndicatorTask() {
      this.isEditing = true;
    },
    handleDeleteSchemeAttachment(att, row) {
      const idx = row.kpiSchemeAttachments.indexOf(att);
      if (idx > -1) {
        row.kpiSchemeAttachments.splice(idx, 1);
        if (att.id) {
          this.attachmentsToDelete.push(att.id);
        }
      }
    },
    handleSchemeSuccess(row, response, file, fileList) {
      const idx = this.indicatorDetailScheme.indexOf(row)
      if (idx != -1) {
        this.schemeFileLists[idx] = fileList
      }
      const attachment = {
        filePath: response.data
      }
      row.kpiSchemeAttachments.push(attachment)
    },
    addSchemeRow() {
      this.indicatorDetailScheme.push({
        id: null,
        indicatorDetailId: '',
        schemeContent: '',
        status: '未审批',
        kpiSchemeAttachments: []
      })
      this.schemeFileLists.push([])
    },
    deleteSchemeRow(index) {
      const row = this.indicatorDetailScheme[index];
      if (!row || !row.id) {
        this.indicatorDetailScheme.splice(index, 1);
        return;
      }
      this.$confirm('确定删除该行方案吗？', '提示', {type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消'}).then(() => {
        this.$http.delete(`/kpi/detail/scheme/${row.id}`).then(response => {
          if (response.data.code === 1) {
            this.$message.success('删除成功');
            this.indicatorDetailScheme.splice(index, 1);
          } else {
            this.$message.error('删除失败');
          }
        })
      })
    },
    submitScheme() {
      const indicatorDetailScheme = this.indicatorDetailScheme.map(item => ({
        ...item,
        indicatorDetailId: this.kpiDetailId
      }));
      const submitSchemeDTO = {
        indicatorDetailSchemes: indicatorDetailScheme,
        attachmentsToDelete: this.attachmentsToDelete
      }
      console.log(JSON.stringify(submitSchemeDTO, null, 2))
      this.$http.post("/kpi/detail/scheme/addOrUpdate", submitSchemeDTO).then((response) => {
        if (response.data.code == 1) {
          this.$message.success("方案提交成功，请等待审批");
          this.attachmentsToDelete = [];
          this.isSchemeEditing = false
        } else {
          this.$message.error("提交失败");
        }
      });
    },
    editScheme() {
      this.isSchemeEditing = true
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    handleContentClick(row, event) {
      // 如果内容为空，阻止事件冒泡，允许输入
      if (!row.contentSummary || row.contentSummary.trim() === '') {
        event.stopPropagation();
      } else {
        // 如果有内容，调用跳转逻辑
        console.log(row)
        this.viewSchemeTaskStatus(row, {property: 'contentSummary'});

      }
    },
    viewSchemeTaskStatus(row, column, cell, event) {
      if (column.property === 'contentSummary') {
        const startDate = Date.parse(new Date(row.startTime.replace(/-/g, "/")))
        const endDate = Date.parse(new Date(row.endTime.replace(/-/g, "/")))
        let EndDateForGantt;
        if (typeof row.actualFinishingTime === 'string' && row.actualFinishingTime) {
          EndDateForGantt = Date.parse(new Date(row.actualFinishingTime.replace(/-/g, "/")));
        } else if (typeof row.delayApprovedDate === 'string' && row.delayApprovedDate) {
          EndDateForGantt = Date.parse(new Date(row.delayApprovedDate.replace(/-/g, "/")));
        } else {
          EndDateForGantt = Date.parse(new Date(row.endTime.replace(/-/g, "/")));
        }
        const originalDuration = Math.floor((endDate - startDate) / (24 * 3600 * 1000)) + 1
        const totalDuration = Math.floor((EndDateForGantt - startDate) / (24 * 3600 * 1000)) + 1
        const progress = originalDuration / totalDuration
        const currentTask = {
          id: row.id,
          title: row.title,
          sn: row.sn,
          parent: row.parentId,
          createTime: row.createTime,
          releaseBy: row.releaseBy,
          reportBy: row.reportBy,
          processInstanceId: row.processInstanceId,
          start_date: moment(row.startTime).format("YYYY-MM-DD HH:mm:ss"),
          end_date: moment(row.endTime).format("YYYY-MM-DD HH:mm:ss"),
          progress: progress,
          text: row.title,
          projectSn: row.projectSn,
          frequency: row.frequency,
          statusName: row.statusName,
          reportComplete: row.reportComplete,
          reportCount: row.reportCount,
          categoryName: row.categoryName,
          originalDuration: originalDuration,
          duration: totalDuration,
          contentSummaries: row.contentSummaries,
          taskMilestones: row.taskMilestones,
          releaseAttachments: row.releaseAttachments,
          reportAttachments: row.reportAttachments,
          commentAttachments: row.commentAttachments,
          completeAttachments: row.completeAttachments,
          taskCommentSummaries: row.taskCommentSummaries,
          taskCompleteSummaries: row.taskCompleteSummaries,
          taskPlanSummaries: row.taskPlanSummaries,
          taskCoordinateSummaries: row.taskCoordinateSummaries,
          taskHistoryDelayVOS: row.taskHistoryDelayVOS,
          latestTaskCompleteApplyVO: row.latestTaskCompleteApplyVO,
          latestTaskDelayApplyVO: row.latestTaskDelayApplyVO
        }
        console.log("工作计划中任务数据跳转到任务详情页面的数据：" + JSON.stringify(currentTask, null, 2))
        this.$store.dispatch("updateCurrentTask", currentTask).then(() => {
          this.$router.push("/task_tool_tip");
        })
      }
    },
    updateSchemeTask(row) {
      if (row.dateRange && row.dateRange.length === 2) {
        row.startTime = row.dateRange[0];
        row.endTime = row.dateRange[1];

        // 计算汇报次数
        if (row.frequency === '周') {
          const startDate = new Date(row.startTime);
          const endDate = new Date(row.endTime);
          if (endDate >= startDate) {
            const diffDays = Math.floor((endDate - startDate) / (1000 * 60 * 60 * 24));
            row.reportCount = Math.max(1, Math.ceil((diffDays + 1) / 7));
          } else {
            row.reportCount = '';
          }
        } else {
          row.reportCount = '';
        }
      } else {
        row.startTime = '';
        row.endTime = '';
        row.reportCount = '';
      }
    },
    handleTaskSuccess(row, response, file, fileList) {
      const attachment = {
        filePath: response.data,
        source: '发布时',
        taskId: ''
      }
      row.releaseAttachments.push(attachment)
    },
    handleDeleteTaskAttachment(att, row) {
      const idx = row.releaseAttachments.indexOf(att);
      if (idx > -1) {
        row.releaseAttachments.splice(idx, 1);
      }
    },
    addTaskRow() {
      const newId = this.schemeTasks.length
          ? Math.max(...this.schemeTasks.map(item => item.id)) + 1
          : 1;
      this.schemeTasks.push({
        id: '',
        sn: "",
        processInstanceId: "",
        categoryId: "",
        title: "",
        createTime: "",
        releaseBy: "",
        reportBy: "",
        frequency: "周",
        reportComplete: "",
        reportCount: "",
        startTime: "",
        endTime: "",
        dateRange: [],
        contentSummaries: [
          {
            id: "",
            taskContentId: "",
            contentSummary: ""
          }
        ],
        taskMilestones: [],
        reportAttachments: [],
        commentAttachments: [],
        taskCommentSummaries: [],
        taskCompleteSummaries: [],
        taskPlanSummaries: [],
        taskCoordinateSummaries: [],
        taskHistoryDelayVOS: [],
        contentSummary: "",
        releaseAttachments: [],
        isNew: true,
        sort:''
      });
    },
    deleteTaskRow() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要删除的行');
        return;
      }
      // 检查是否有选中的不是新增行
      const hasOldRow = this.selectedRows.some(row => !row.isNew);
      if (hasOldRow) {
        this.$message.warning('只能删除新增的行，已有任务不可删除');
        return;
      }
      this.schemeTasks = this.schemeTasks.filter(
          item => !this.selectedRows.includes(item)
      );
      this.selectedRows = [];
    },
    releaseSchemeTask() {
      // 先校验是否有选中行
      if (!this.selectedRows || this.selectedRows.length === 0) {
        this.$message({
          type: 'warning',
          message: '请至少选择一行工作内容进行发布！',
          showClose: true,
        });
        return;
      }
      // 校验选中行的完成时间和负责人不能为空
      const invalidRow = this.selectedRows.find(row =>
          !row.endTime ||
          !row.contentSummary ||
          !row.reportBy ||
          !Array.isArray(row.reportBy) ||
          row.reportBy.length < 2 ||
          !row.reportBy[1] ||
          row.reportBy[1].trim() === ''
      );
      if (invalidRow) {
        this.$message({
          type: 'warning',
          message: '任务信息不能为空',
          showClose: true,
        });
        return;
      }
      const schemeTasks = this.selectedRows.map(row => ({
        ...row,
        title: this.title,
        contentSummaries: row.contentSummary ? [{contentSummary: row.contentSummary}] : [],
        endTime: moment(row.endTime).tz('Asia/Shanghai').format('YYYY/MM/DD HH:mm:ss'),
        startTime: moment(row.startTime).tz('Asia/Shanghai').format('YYYY/MM/DD HH:mm:ss'),
        reportBy: Array.isArray(row.reportBy) ? row.reportBy[row.reportBy.length - 1] : row.reportBy,
        reportCount: row.reportCount,
        frequency: row.frequency,
        taskMilestones: [],
        releaseAttachments: row.releaseAttachments,
        kpiDetailId: this.kpiDetailId,
        sort:'',
        categoryId:3
      }));
      console.log("发布的任务的数据为" + JSON.stringify(schemeTasks, null, 2))
      this.$http.post('/task/kpi/release/', schemeTasks).then(response => {
        if (response.data.code == 1) {
          this.$message({
            type: 'success',
            message: '发布成功',
            showClose: true,
          });
        } else {
          this.$message({type: 'error', message: '发布失败:', showClose: true});
        }
      });
    },
    selectableRow(row, index) {
      // 只有新增行可选
      return row.isNew === true;
    },
    editSchemeTask() {
      this.isTaskEditing = true
    },
    moveArrayElement(array, oldIndex, newIndex) {
      if (oldIndex < 0 || oldIndex >= array.length || newIndex < 0 || newIndex >= array.length) {
        console.error('Invalid index:', {oldIndex, newIndex, arrayLength: array.length});
        return;
      }
      const element = array.splice(oldIndex, 1)[0];
      array.splice(newIndex, 0, element);
      // 强制触发响应式更新
      this.schemeTasks = [...this.schemeTasks];
    },
    initDragSortTableRow() {
      const tbody = this.$refs.table.$el.querySelector('.el-table__body-wrapper > table > tbody');
      this.sortable = Sortable.create(tbody, {
        animation: 150,
        ghostClass: 'ghostClass',
        onEnd: e => {
          const {oldIndex, newIndex} = e;
          this.moveArrayElement(this.schemeTasks, oldIndex, newIndex);
          this.saveSortOrder(); // 保存新排序到后端
        },
      });
    },
    saveSortOrder() {
      const schemeTaskSortDTOS = this.schemeTasks.map((schemeTask, index) => ({
        id: schemeTask.id,
        sort: index + 1,
      }));
      this.$http.post('/task/sort/', schemeTaskSortDTOS).then(response => {
      }).catch(err => {
        this.$message.error('排序失败');
      });
    },
  },
  mounted() {
    const user = JSON.parse(localStorage.getItem('user'))
    const {title, kpiDetailId, kpiId, type} = this.$route.query;
    this.kpiDetailId = kpiDetailId
    this.kpiId = kpiId
    this.type = type
    console.log("从路由得到的上一层数据为" + JSON.stringify(this.$route.query, null, 2))
    this.title = title;
    Promise.all([
      this.$http.get(`/kpi/indicator/task/${kpiId}/${kpiDetailId}`),
      this.$http.get(`/kpi/detail/scheme/${kpiDetailId}`),
      this.$http.get(`/kpi/scheme_task/${kpiDetailId}/${type}`)
    ])
        .then(([indicatorTaskResponse, schemeResponse, taskResponse]) => {
          // 第一部分处理指标任务数据
          if (indicatorTaskResponse.data.code === 1) {
            /*console.log("从后端获取的指标任务数据为：" + JSON.stringify(indicatorTaskResponse.data.data, null, 2))*/
            this.indicatorDetailTask = indicatorTaskResponse.data.data || {
              id: '',
              kpiId: this.kpiId,
              title: this.title,
              indicatorDetailId: this.kpiDetailId,
              createTime: moment().format("YYYY/MM/DD"),
              endTime: null,
              personInCharge: '',
              createBy: user.nickName
            }
            if (user.nickName === this.indicatorDetailTask.createBy) {
              this.isCreateBy = true
            }
            if (user.nickName === this.indicatorDetailTask.personInCharge) {
              this.isPersonInCharge = true
              console.log(user.nickName + this.isPersonInCharge)
            }
          } else {
            this.$message.error("kpi指标任务读取错误");
          }
          // 第二部分处理方案数据
          if (schemeResponse.data.code === 1) {
            const data = schemeResponse.data.data;
            if (Array.isArray(data) && data.length > 0) {
              this.indicatorDetailScheme = data;
              this.isSchemeEditing = false
            } else {
              this.indicatorDetailScheme = [{
                id: null,
                indicatorDetailId: '',
                schemeContent: '',
                status: '未审批',
                kpiSchemeAttachments: []
              }];
              this.isSchemeEditing = this.isPersonInCharge
              console.log(this.isSchemeEditing, this.isPersonInCharge)
            }
            // 同步初始化 schemeFileLists
            this.schemeFileLists = this.indicatorDetailScheme.map(() => []);
          } else {
            this.$message.error("方案读取错误");
          }
          // 第三部分处理工作计划数据
          if (taskResponse.data.code === 1) {
            /*
                        console.log("从后端获取的任务数据为" + JSON.stringify(taskResponse.data.data, null, 2))
            */
            const tasks = taskResponse.data.data.map(item => ({
              ...item,
              contentSummary: item.contentSummaries && item.contentSummaries.length > 0
                  ? item.contentSummaries[0].contentSummary : '',
              isNew: false,
              dateRange: [moment(item.startTime).format("YYYY-MM-DD"), moment(item.endTime).format("YYYY-MM-DD")]
            }));
            /*            console.log("后端任务数据转换成前端格式：" + JSON.stringify(tasks, null, 2))*/
            this.schemeTasks = tasks.length > 0 ? tasks : [{
              id: '',
              sn: "",
              processInstanceId: "",
              categoryId: "",
              title: "",
              createTime: "",
              releaseBy: "",
              reportBy: "",
              frequency: "周",
              reportComplete: "",
              reportCount: "",
              startTime: "",
              endTime: "",
              dateRange: [],
              contentSummaries: [
                {
                  id: "",
                  taskContentId: "",
                  contentSummary: ""
                }
              ],
              taskMilestones: [],
              reportAttachments: [],
              commentAttachments: [],
              taskCommentSummaries: [],
              taskCompleteSummaries: [],
              taskPlanSummaries: [],
              taskCoordinateSummaries: [],
              taskHistoryDelayVOS: [],
              contentSummary: "",
              actualFinishingTime: '',
              delayApprovedDate: '',
              releaseAttachments: [],
              statusName: '',
              sort:'',
              isNew: true
            }];
            this.isTaskEditing = tasks.length === 0;
            this.initDragSortTableRow()
          } else {
            this.$message.error("工作计划任务读取错误");
          }
        })
        .catch(error => {
          this.$message.error("数据加载失败：" + error.message);
        });
  }
}
</script>
<style scoped>
::v-deep .ghostClass {
  background-color: #ecf5ff;
}

::v-deep .ghostClass td {
  border-bottom-color: #409eff;
}
</style>